<template>
  <div class="state-machine-panel">
    <a-card title="状态机配置" size="small">
      <template #extra>
        <a-space>
          <a-button
            type="primary"
            size="small"
            @click="showCreateEventModal = true"
          >
            <template #icon>
              <IconifyIcon icon="ant-design:plus-outlined" />
            </template>
            新建事件
          </a-button>
          <a-button size="small" @click="generateDiagram">
            <template #icon>
              <IconifyIcon icon="ant-design:branches-outlined" />
            </template>
            生成状态图
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="stateMachineEvents"
        :pagination="false"
        size="small"
        row-key="id"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'from'">
            <a-tag v-for="status in record.from" :key="status" color="blue">
              {{ status }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'to'">
            <a-tag color="green">{{ record.to }}</a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="editEvent(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个事件吗？"
                @confirm="removeEvent(index)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 事件编辑模态框 -->
    <a-modal
      :open="showCreateEventModal"
      :title="editingEvent ? '编辑事件' : '新建事件'"
      @ok="saveEvent"
      @cancel="resetEventForm"
    >
      <a-form
        ref="eventFormRef"
        :model="eventForm"
        :rules="eventRules"
        layout="vertical"
      >
        <a-form-item label="事件名称" name="name">
          <a-input
            v-model:value="eventForm.name"
            placeholder="请输入事件名称"
          />
        </a-form-item>

        <a-form-item label="起始状态" name="from">
          <a-select
            v-model:value="eventForm.from"
            mode="multiple"
            placeholder="选择起始状态"
            style="width: 100%"
          >
            <a-select-option
              v-for="status in availableStatuses"
              :key="status.code"
              :value="status.code"
            >
              {{ status.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="目标状态" name="to">
          <a-select
            v-model:value="eventForm.to"
            placeholder="选择目标状态"
            style="width: 100%"
          >
            <a-select-option
              v-for="status in availableStatuses"
              :key="status.code"
              :value="status.code"
            >
              {{ status.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="转换条件" name="conditions">
          <a-textarea
            v-model:value="eventForm.conditions"
            placeholder="请输入转换条件（可选）"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="转换动作" name="actions">
          <a-textarea
            v-model:value="eventForm.actions"
            placeholder="请输入转换动作（可选）"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
interface Props {
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  stateMachineUpdated: [];
}>();

// 响应式数据
const showCreateEventModal = ref(false);
const editingEvent = ref<any>(null);

// 可用状态
const availableStatuses = ref([
  { code: 'PENDING_REVIEW', name: '待审核' },
  { code: 'APPROVED', name: '已审核' },
  { code: 'REJECTED', name: '已拒绝' },
  { code: 'ACTIVE', name: '已激活' },
  { code: 'SUSPENDED', name: '已暂停' },
  { code: 'ARCHIVED', name: '已归档' },
]);

// 状态机事件
const stateMachineEvents = ref([
  {
    id: '1',
    name: '审核通过',
    from: ['PENDING_REVIEW'],
    to: 'APPROVED',
    conditions: '审核通过',
    actions: '发送通知',
  },
  {
    id: '2',
    name: '审核拒绝',
    from: ['PENDING_REVIEW'],
    to: 'REJECTED',
    conditions: '审核拒绝',
    actions: '发送拒绝通知',
  },
  {
    id: '3',
    name: '激活资源',
    from: ['APPROVED'],
    to: 'ACTIVE',
    conditions: '资源准备就绪',
    actions: '更新资源状态',
  },
]);

// 表单数据
const eventFormRef = ref();
const eventForm = reactive({
  id: '',
  name: '',
  from: [] as string[],
  to: '',
  conditions: '',
  actions: '',
});

// 表单验证规则
const eventRules = {
  name: [{ required: true, message: '请输入事件名称' }],
  from: [{ required: true, message: '请选择起始状态' }],
  to: [{ required: true, message: '请选择目标状态' }],
};

// 表格列定义
const columns = [
  { title: '事件名称', dataIndex: 'name', key: 'name' },
  { title: '起始状态', key: 'from' },
  { title: '目标状态', key: 'to' },
  { title: '条件', dataIndex: 'conditions', key: 'conditions' },
  { title: '动作', dataIndex: 'actions', key: 'actions' },
  { title: '操作', key: 'action', width: 120 },
];

// 方法
const editEvent = (record: any) => {
  editingEvent.value = record;
  Object.assign(eventForm, record);
  showCreateEventModal.value = true;
};

const removeEvent = (index: number) => {
  stateMachineEvents.value.splice(index, 1);
  message.success('删除成功');
  emit('stateMachineUpdated');
};

const saveEvent = async () => {
  try {
    await eventFormRef.value.validate();

    if (editingEvent.value) {
      const index = stateMachineEvents.value.findIndex(
        (item) => item.id === editingEvent.value.id,
      );
      if (index !== -1) {
        stateMachineEvents.value[index] = { ...eventForm };
      }
      message.success('事件更新成功');
    } else {
      const newEvent = {
        ...eventForm,
        id: Date.now().toString(),idid
      };
      stateMachineEvents.value.push(newEvent);
      message.success('事件创建成功');
    }

    showCreateEventModal.value = false;
    resetEventForm();
    emit('stateMachineUpdated');
  } catch (error) {
    message.error('保存失败');
  }
};

const resetEventForm = () => {
  editingEvent.value = null;
  eventFormRef.value?.resetFields();
  Object.assign(eventForm, {
    id: '',
    name: '',
    from: [],
    to: '',
    conditions: '',
    actions: '',
  });
};

const generateDiagram = () => {
  message.success('状态图生成功能开发中...');
};

// 初始化
onMounted(() => {
  // 这里可以加载实际的状态机配置数据
});
</script>

<style lang="less" scoped>
.state-machine-panel {
  .ant-table {
    .ant-table-tbody > tr > td {
      padding: 8px;
    }
  }
}
</style>
